import { useEventListener } from "@/hooks/useEventListener";
import { ChessTeam } from "@/third/chinese-chess/src/demo/chess";
import { useEffect, useMemo, useRef, useState } from "react";
import { Space } from "../Main/Space";
import { ChessNode } from "./ChessNode";
import styles from "./style.module.css";

export default function Chess() {
  const ref_root = useRef<HTMLDivElement>(null);
  const ref_bg_canvas = useRef<HTMLCanvasElement>(null);
  const ref_fg_canvas = useRef<HTMLCanvasElement>(null);
  const [canvas_size, set_canvas_size] = useState<[number, number]>([1, 1])
  const [canvas_style, set_canvas_style] = useState<React.CSSProperties>({})
  const [cell_size, set_cell_size] = useState<number>(50)

  const board = useMemo(() => {
    return new ChessNode()
  }, [])

  const auto_resize = () => {
    const w = ref_root.current?.clientWidth!
    set_cell_size(Math.max(1, Math.min(w / 10, 100)))
  }
  useEventListener(window, 'resize', auto_resize)

  useEffect(() => {
    board.cell_size = cell_size
    board.y = 40;
    board.init(ref_bg_canvas.current, ref_fg_canvas.current)
    const scale = board.cavans_scale = 1 * (window.devicePixelRatio ?? 1)
    const w = board.width + 4 + board.x
    const h = board.height + 4 + board.y
    set_canvas_style({ width: w, height: h })
    set_canvas_size([scale * w, scale * h])
    let prev_time: number = 0;
    let r_id = 0
    const render = (time: number) => {
      if (time > 0 && prev_time > 0) {
        const dt = time - prev_time;
        board.draw(dt, time);
        const bg_ctx = board.bg_ctx;
        if (bg_ctx) {
          bg_ctx.textBaseline = 'top'
          bg_ctx.textAlign = 'left'
          bg_ctx.font = `normal ${cell_size * 0.25}px serif`;
          const t = board.board.acting_player?.team;
          if (t === ChessTeam.Wht) {
            bg_ctx.fillStyle = 'black'
            bg_ctx.fillText("Chess side：White", 5, 10)
          }
          else if (t === ChessTeam.Blk) {
            bg_ctx.fillStyle = 'black'
            bg_ctx.fillText("Chess side：Black", 5, 10)
          }
        }

      }
      prev_time = time
      r_id = requestAnimationFrame(render)
    }
    render(0);
    auto_resize()
    return () => {
      board.release();
      cancelAnimationFrame(r_id)
    };
  }, [board, cell_size])

  return (
    <div className={styles.chinese_chess_root} ref={ref_root}>
      <Space vertical>
        <div className={styles.layer_container}>
          <canvas ref={ref_bg_canvas}
            width={canvas_size[0]}
            height={canvas_size[1]}
            className={styles.board_layer}
            draggable={false}
            style={canvas_style}
            onContextMenu={e => e.preventDefault()} />
          <canvas ref={ref_fg_canvas}
            width={canvas_size[0]}
            height={canvas_size[1]}
            className={styles.pieces_layer}
            draggable={false}
            style={canvas_style}
            onContextMenu={e => e.preventDefault()} />
        </div>
      </Space>
    </div>
  )
}